package com.bdqn.controller;
import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.SysRole;
import com.bdqn.service.SysRoleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/role")
public class SysRoleController {
    @Resource
    private SysRoleService sysRoleService;
    @RequestMapping("/list")
    public String getUserList(Model model, @RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysRole> all = sysRoleService.getAll();
        model.addAttribute("roleList",all);
        return "/sysRole/list";
    }
    @PostMapping("/add")
    public String add(String code,String roleName){
        int add = sysRoleService.add(code, roleName);
        return "redirect:/role/list";
    }
    @ResponseBody
    @GetMapping("/simpleList")
    public String roleList(Model model) {
        List<SysRole> roleList = sysRoleService.getAll();
        model.addAttribute("roleList", roleList);
        return JSON.toJSONString(roleList);
    }
    @ResponseBody // 原样返回字符串
    @GetMapping("/del/{roleid}")
    public String del(@PathVariable int roleid){
        Map<String,String> map = new HashMap<>();
        int roleId = sysRoleService.del(roleid);
        if (roleId == 1){
            map.put("delResult","true");
        }else {
            map.put("delResult","false");
        }
        return JSON.toJSONString(map);
    }
    @RequestMapping("/toAdd")
    public String getAdd(){
        return "/sysRole/add";
    }
    @ResponseBody // 让返回值原样输出
    @GetMapping("/codeExist")
    public String add(String code){
        int codeString = sysRoleService.getCode(code);
        Map<String,Integer> map = new HashMap<>();
        if (codeString == 1){
            map.put("exist",1);
        }else{
            map.put("exist",0);
        }
        return JSON.toJSONString(map);
    }
    @RequestMapping("/toUpdate/{roleid}")
    public String toUpdate(@PathVariable String roleid,Model model){
        model.addAttribute("sysRole",sysRoleService.getByID(roleid));
        return "sysRole/update";
    }
    @PostMapping("/update")
    public String update(Integer id,String code,String roleName){
        int upd = sysRoleService.upd(id,code,roleName);
        return "redirect:/role/list";
    }
}
